
// Handles details of using FB for an external login
var _cloud = require('ti.cloud');
var _user = null;
var _loginCallback = null;
var _logoutCallback = null;
var _loggedIn = false;

// Set up variables
Ti.Facebook.appid = '456509711040484';  // Need the Facebook app id
Ti.Facebook.permissions = [];  // App permissions on FB. Only need to login.

// Add login handler
Ti.Facebook.addEventListener('login', function (e) {
	if (e.success) {
		loginViaFacebook(Ti.Facebook.getAccessToken());
	} else if (e.error) {

	} else if (e.cancelled) {

	}
});

// Add logout handler
Ti.Facebook.addEventListener('logout', function () {
	_user = null;
	_loggedIn = false;
	_logoutCallback();
});

function loginViaFacebook(token) {
	_cloud.SocialIntegrations.externalAccountLogin ({
		type: 'facebook',
		token: token
	}, function (e) {
		if (e.success) {
			_user = e.users[0];
			_loggedIn = true;
			_loginCallback(_user);
		} else {
			_user = null;
			_loggedIn = false;
		}
	});
}

exports.login = function (loginCallback) {
	_loginCallback = loginCallback;
	Ti.Facebook.authorize();
}

exports.logout = function(logoutCallback) {
	_logoutCallback = logoutCallback;
	Ti.Facebook.logout();
}

exports.isLoggedIn = function () {
	return _loggedIn;
}

exports.user = _user;